package grape.wx.rest.mp;

import grape.wx.service.mp.MpProperties;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 重写了几个方法，目的是兼容appCode，建议用appCode替代appId做为参数，这样换了公众号不影响配置或代码
 * Created by yangwei
 * Created at 2020/7/22 12:49
 */
public class CustomWxMpServiceImpl extends WxMpServiceImpl {

    @Autowired
    private MpProperties mpProperties;

    @Override
    public void addConfigStorage(String mpId, WxMpConfigStorage configStorages) {
        super.addConfigStorage(getByAppCode(mpId), configStorages);
    }

    @Override
    public void removeConfigStorage(String mpId) {
        super.removeConfigStorage(getByAppCode(mpId));
    }

    @Override
    public WxMpService switchoverTo(String mpId) {
        return super.switchoverTo(getByAppCode(mpId));
    }

    @Override
    public boolean switchover(String mpId) {
        return super.switchover(getByAppCode(mpId));
    }

    /**
     * 根据appCode查找配置的appId,如果没有找到，返回appCode
     * @param appCode
     * @return 返回appCode如果没有找到，否则返回appId
     */
    private String getByAppCode(String appCode){

        if (mpProperties.getConfigs() != null) {
            return mpProperties.getConfigs().stream()
                    .filter(item -> StringUtils.equals(appCode, item.getAppCode()))
                    .map(MpProperties.MpConfig::getAppId)
                    .findFirst().orElse(appCode);
        }

        return appCode;
    }
}
